package com.xgjweb.fsi.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import com.xgjweb.common.dao.ICommonDao;
import com.xgjweb.common.service.CommonServiceImpl;
import com.xgjweb.common.utils.Constant;
import com.xgjweb.common.utils.XgjWebLogger;
import com.xgjweb.common.utils.XgjWebUtils;
import com.xgjweb.fsi.domain.Condition;
import com.xgjweb.fsi.domain.User;

/**
 * 
 * @author xgj
 * 
 */
public class UserServiceImpl extends CommonServiceImpl implements IUserService {
	private ICommonDao userDao;

	public void setUserDao(ICommonDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 用户登录
	 */
	public User login(User user) throws Exception {
		try {
			User userOld = null;
			userOld = new User();
			userOld.setName(user.getName());
			userOld.setStatementName("selectUserByName");
			userOld = (User) userDao.selectByObject(userOld);
			if (userOld == null) {
				return null;
			}
			if (!XgjWebUtils.processPwd(user.getPassword()).equals(
					userOld.getPassword())) {
				return null;
			}
			return userOld;
		} catch (Exception e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}

	}

	/**
	 * 注册
	 */
	public String register(User user) throws Exception {
		try {
			User userOld = new User();
			userOld.setName(user.getName());
			userOld.setStatementName("selectUserByName");
			userOld = (User) userDao.selectByObject(userOld);
			if (userOld == null) {
				user.setStatementName("insertUser");
				user.setPassword(XgjWebUtils.processPwd(user.getPassword()));
				userDao.insert(user);
				return successForFlex("注册成功");
			} else {
				return errorForFlex("该用户已经存在");
			}
		} catch (Exception e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * 修改
	 */
	public String updateInfo(User user) throws Exception {
		try {
			user.setStatementName("updateUserById");
			if (user.getPassword() != null)
				user.setPassword(XgjWebUtils.processPwd(user.getPassword()));
			userDao.update(user);
			return successForFlex("info_修改信息成功");
		} catch (Exception e) {
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}

	}

	/**
	 * 图片修改
	 */
	@SuppressWarnings("unchecked")
	public void imageChange(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		File newFile =null;
		try {
			request.setCharacterEncoding("UTF-8");
			String path = Constant.PIC_PATH;
			RequestContext requestContext = new ServletRequestContext(request);
			// 用uuid生成文件名
			String filename = XgjWebUtils.getUUID();
			if (FileUpload.isMultipartContent(requestContext)) {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置文件最大为50kb
				upload.setSizeMax(1024 * 50);
				List<?> items = new ArrayList();
				items = upload.parseRequest(request);
				Iterator<?> it = items.iterator();
				while (it.hasNext()) {
					FileItem fileItem = (FileItem) it.next();
					if (!fileItem.isFormField()) {
						if (fileItem.getName() != null
								&& fileItem.getSize() != 0) {
							// 组织文件名和文件后缀
							filename = filename + "."
									+ fileItem.getName().split("\\.")[1];
							newFile = new File(path + File.separator
									+ filename);
							//保存文件
							fileItem.write(newFile);
							User user = new User();
							user.setStatementName("selectUserByID");
							user.setId(Integer.parseInt(request
									.getParameter("id")));
							user=(User)userDao.selectByObject(user);
							//删除旧的图片
							String oldPic=user.getPicture();
							if(!Constant.DEFAOULT_PIC.equals(oldPic)){
								//如果不是默认的default.jpg就可以删除
								File oldPicFile=new File(Constant.PIC_PATH+oldPic);
								if(oldPicFile.exists()){
									oldPicFile.delete();
								}
							}
							//保存图片名字
							user.setPicture(filename);
							// 更新数据库信息
							updateInfo(user);
							// 返回图片名称
							response.getWriter().print(filename);
							response.getWriter().flush();
							response.getWriter().close();
						}
					}

				}
			}
		} catch (Exception e) {
			//发生异常把保存的新图片删除。
			if(newFile!=null && newFile.exists()){
				newFile.delete();
			}
			XgjWebLogger.getInstance().error(e.getMessage(), e);
			throw e;
		}
	}
}
